package org.jctc.els.modules.biz.service.proTemplate.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.jctc.els.modules.biz.entity.proTemplate.ProjectReviewTemplateDetailed;
import org.jctc.els.modules.biz.entity.proTemplate.ProjectReviewTemplateDetailedVO;
import org.jctc.els.modules.biz.entity.proTemplate.ProjectReviewTemplateOptions;
import org.jctc.els.modules.biz.entity.proTemplate.TemplateDetailedTree;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateDetailedMapper;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateOptionsMapper;
import org.jctc.els.modules.biz.service.proTemplate.ProjectReviewTemplateDetailedService;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 评审模板明细表;(els_project_review_template_detailed)表服务实现类
 *
 * @author : http://www.chiner.pro
 * @date : 2022-6-21
 */
@Service
public class ProjectReviewTemplateDetailedServiceImpl implements ProjectReviewTemplateDetailedService {
    @Autowired
    private ProjectReviewTemplateDetailedMapper projectReviewTemplateDetailedMapper;

    @Autowired
    private ProjectReviewTemplateOptionsMapper projectReviewTemplateOptionsMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public ProjectReviewTemplateDetailed queryById(Long id) {
        return projectReviewTemplateDetailedMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param projectReviewTemplateDetailed 筛选条件
     * @param current                       当前页码
     * @param size                          每页大小
     * @return
     */
    public Page<ProjectReviewTemplateDetailed> paginQuery(ProjectReviewTemplateDetailed projectReviewTemplateDetailed, long current, long size) {
        //1. 构建动态查询条件
        LambdaQueryWrapper<ProjectReviewTemplateDetailed> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(projectReviewTemplateDetailed.getName())) {
            queryWrapper.eq(ProjectReviewTemplateDetailed::getName, projectReviewTemplateDetailed.getName());
        }
        if (StrUtil.isNotBlank(projectReviewTemplateDetailed.getParentIdPath())) {
            queryWrapper.eq(ProjectReviewTemplateDetailed::getParentIdPath, projectReviewTemplateDetailed.getParentIdPath());
        }
        if (StrUtil.isNotBlank(projectReviewTemplateDetailed.getOptionIds())) {
            queryWrapper.eq(ProjectReviewTemplateDetailed::getOptionIds, projectReviewTemplateDetailed.getOptionIds());
        }
        if (StrUtil.isNotBlank(projectReviewTemplateDetailed.getRemark())) {
            queryWrapper.eq(ProjectReviewTemplateDetailed::getRemark, projectReviewTemplateDetailed.getRemark());
        }
        //2. 执行分页查询
        Page<ProjectReviewTemplateDetailed> pagin = new Page<>(current, size, true);
        IPage<ProjectReviewTemplateDetailed> selectResult = projectReviewTemplateDetailedMapper.selectByPage(pagin, queryWrapper);
        pagin.setPages(selectResult.getPages());
        pagin.setTotal(selectResult.getTotal());
        pagin.setRecords(selectResult.getRecords());
        //3. 返回结果
        return pagin;
    }

    /**
     * 新增数据
     *
     * @param projectReviewTemplateDetailed 实例对象
     * @return 实例对象
     */
    public ProjectReviewTemplateDetailed insert(ProjectReviewTemplateDetailed projectReviewTemplateDetailed) {
        projectReviewTemplateDetailedMapper.insert(projectReviewTemplateDetailed);
        return projectReviewTemplateDetailed;
    }

    /**
     * 更新数据
     *
     * @param projectReviewTemplateDetailed 实例对象
     * @return 实例对象
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ProjectReviewTemplateDetailedVO projectReviewTemplateDetailed) {
        Boolean result = false;
        List<ProjectReviewTemplateOptions> optionList = projectReviewTemplateDetailed.getOptionList();
        //判断是否有选项 有选项的话更新选项
        if (optionList.size() > 0) {
            String optionIds = projectReviewTemplateDetailed.getOptionIds();
            String[] split = optionIds.split(",");
            List<String> optionIdList = Arrays.asList(split);
            if (optionIdList.size() > 0 && !optionIdList.get(0).equals("")) {
                result = projectReviewTemplateOptionsMapper.deleteBatchIds(optionIdList) > 0;
                if (BooleanUtil.isFalse(result)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
            List<Long> newOptionList = new ArrayList<>();
            for (ProjectReviewTemplateOptions projectReviewTemplateOptions : optionList) {
                Long projectReviewId = projectReviewTemplateDetailed.getProjectReviewId();
                projectReviewTemplateOptions.setProjectReviewId(projectReviewId);
                projectReviewTemplateOptions.setId(IdUtil.getSnowflakeNextId());
                projectReviewTemplateOptionsMapper.save(projectReviewTemplateOptions);
                newOptionList.add(projectReviewTemplateOptions.getId());
            }
            StringBuilder sb = new StringBuilder();
            if (newOptionList.size() > 0){
                for (int i = 0; i < newOptionList.size(); i++) {
                    if (i == newOptionList.size() - 1) {
                        sb.append(String.valueOf(newOptionList.get(i)));
                    } else {
                        sb.append(String.valueOf(newOptionList.get(i)));
                        sb.append(",");
                    }
                }
                projectReviewTemplateDetailed.setOptionIds(sb.toString());
            }
        }
        result = projectReviewTemplateDetailedMapper.updateById(projectReviewTemplateDetailed) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Long id) {
        int total = projectReviewTemplateDetailedMapper.deleteById(id);
        return total > 0;
    }

    @Override
    public ProjectReviewTemplateDetailedVO selectDetailedById(Long id) {
        ProjectReviewTemplateDetailedVO detailedVO = projectReviewTemplateDetailedMapper.selectDetailedById(id);

        if (ObjectUtil.isNotNull(detailedVO.getOptionIds())) {
            String optionIds = detailedVO.getOptionIds();
            String[] split = optionIds.split(",");
            List<ProjectReviewTemplateOptions> optionsList = projectReviewTemplateOptionsMapper.selectList(new QueryWrapper<ProjectReviewTemplateOptions>().in("id", split));
            detailedVO.setOptionList(optionsList);
        }
        return detailedVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteBatchIds(List<String> ids) {
        Boolean result = false;
        //判断是否有选项
        for (String string : ids) {
            ProjectReviewTemplateDetailed detailed = projectReviewTemplateDetailedMapper.selectById(string);
            Integer canOptions = detailed.getCanOptions();
            if (canOptions == 1) {
                String optionIds = detailed.getOptionIds();
                String[] split1 = optionIds.split(",");
                List<String> strings1 = Arrays.asList(split1);
                result = projectReviewTemplateOptionsMapper.deleteBatchIds(strings1) > 0;
                if (BooleanUtil.isFalse(result)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new ServiceException("操作失败");
                }
            }
        }
        result = projectReviewTemplateDetailedMapper.deleteBatchIds(ids) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException("操作失败");
        }
        return result;
    }

    @Override
    public List<TemplateDetailedTree> selectList(Long projectReviewId) {
        List<TemplateDetailedTree> list = projectReviewTemplateDetailedMapper.selectTreeList(projectReviewId);
        List<TemplateDetailedTree> childrenList = findByParentId(list, 0L);
        return childrenList;
    }

    private List<TemplateDetailedTree> listToSetTree(List<ProjectReviewTemplateDetailedVO> listByPage) {
        List<TemplateDetailedTree> child = CollUtil.newArrayList();
        for (ProjectReviewTemplateDetailedVO category : listByPage) {
            TemplateDetailedTree childNode = new TemplateDetailedTree();
            childNode.setId(category.getId());
            childNode.setTitle(category.getName());
            childNode.setParentId(category.getParentId());
            childNode.setExpand(false);
            List<TemplateDetailedTree> child2 = CollUtil.newArrayList();
            for (ProjectReviewTemplateDetailedVO categoryVO : category.getChildren()) {
                TemplateDetailedTree childNode1 = new TemplateDetailedTree();
                childNode1.setId(categoryVO.getId());
                childNode1.setTitle(categoryVO.getName());
                childNode1.setParentId(categoryVO.getParentId());
                childNode1.setExpand(false);
                child2.add(childNode1);
            }
            childNode.setChildren(child2);
            child.add(childNode);
        }
        return child;
    }

    private List<TemplateDetailedTree> findByParentId(List<TemplateDetailedTree> list, Long parentId) {
        List<TemplateDetailedTree> list1 = new ArrayList<>();
        for (TemplateDetailedTree commentsVO : list) {
            if (commentsVO.getParentId().equals(parentId) && !commentsVO.getId().equals(parentId)) {
                commentsVO.setChildren(findByParentId(list, commentsVO.getId()));
                list1.add(commentsVO);
            }
        }
        return list1;
    }
}
